<template>
  <Page class="bg-[#f5f5f5] min-h-screen pb-[120rpx]">
    <!-- 头部 -->
    <PageHeader title="编辑个人简介" :showBack="true"/>
    
    <!-- 基本信息 -->
    <view class="bg-white rounded-[24rpx] shadow-md mx-[24rpx] mt-[32rpx] p-[32rpx]">
      <view class="flex items-center mb-[24rpx]">
        <!-- <IconFont name="user" class="text-[32rpx] text-[#165DFF] mr-[12rpx]" /> -->
        <text class="text-[32rpx] font-bold text-[#165DFF]">基本信息</text>
      </view>
      
      <!-- 头像上传 -->
      <view class="flex items-center mb-[32rpx]">
        <image 
          :src="formData.avatarUrl || 'http://www.dzgktf.com/templets/default/images/wtyt.jpg'"
          class="w-[120rpx] h-[120rpx] rounded-full mr-[24rpx] object-cover border-2 border-[#f0f0f0]"
        />
        <nut-button 
          type="primary" 
          class="rounded-[20rpx] text-[28rpx] bg-[#f5f5f5] text-[#666] border border-[#ddd]"
          @click="chooseAvatar"
        >
          更换头像
        </nut-button>
      </view>
      
      <!-- 昵称 -->
      <view class="mb-[24rpx]">
        <text class="block text-[28rpx] text-[#666] mb-[12rpx]">昵称</text>
        <nut-input 
          v-model="formData.name"
          placeholder="请输入您的昵称"
          class="rounded-[16rpx] border border-[#ddd]"
        />
      </view>
      
      <!-- 个人简介 -->
      <view class="mb-[24rpx]">
        <text class="block text-[28rpx] text-[#666] mb-[12rpx]">个人简介</text>
        <nut-textarea 
          v-model="formData.briefIntroduction"
          placeholder="介绍一下你自己..."
          :rows="4"
          class="rounded-[16rpx] border border-[#ddd]"
        />
      </view>
    </view>

    <!-- 技能掌握 -->
    <view class="bg-white rounded-[24rpx] shadow-md mx-[24rpx] mt-[24rpx] p-[32rpx]">
      <view class="flex items-center mb-[24rpx]">
        <!-- <IconFont name="tools" class="text-[32rpx] text-[#165DFF] mr-[12rpx]" /> -->
        <text class="text-[32rpx] font-bold text-[#165DFF]">技能掌握</text>
      </view>
      
      <!-- 添加技能 -->
      <view class="flex mb-[24rpx]">
        <nut-input 
          v-model="newSkill" 
          placeholder="输入技能后点击添加"
          class="flex-1 rounded-l-[16rpx] border border-[#ddd]"
          @keypress="onSkillKeyPress"
        />
        <nut-button 
          type="primary" 
          class="rounded-r-[16rpx] text-[28rpx] bg-[#165DFF] border-none"
          @click="addSkill"
        >
          添加
        </nut-button>
      </view>
      
      <!-- 技能标签 -->
      <view class="flex flex-wrap gap-[16rpx]">
        <view 
          v-for="(skill, index) in formData.skills" 
          :key="index"
          class="flex items-center bg-[#e3f2fd] text-[#165DFF] px-[20rpx] py-[12rpx] rounded-[30rpx] text-[26rpx]"
        >
          <text>{{ skill }}</text>
          <IconFont 
            name="close" 
            size="10"
            class="ml-[12rpx] text-[24rpx] text-[#999] cursor-pointer" 
            @click="removeSkill(index)"
          />
        </view>
      </view>
    </view>

    <!-- 服务范围 -->
    <view class="bg-white rounded-[24rpx] shadow-md mx-[24rpx] mt-[24rpx] p-[32rpx]">
      <view class="flex items-center mb-[24rpx]">
        <!-- <IconFont name="briefcase" class="text-[32rpx] text-[#165DFF] mr-[12rpx]" /> -->
        <text class="text-[32rpx] font-bold text-[#165DFF]">服务范围</text>
      </view>
      
      <view class="grid grid-cols-2 gap-[24rpx]">
        <label 
          v-for="service in serviceOptions" 
          :key="service.id"
          class="flex items-center cursor-pointer"
        >
          <nut-checkbox 
            v-model="service.checked" 
            class="mr-[12rpx]"
          />
          <text class="text-[28rpx] text-[#333]">{{ service.name }}</text>
        </label>
      </view>
    </view>
    <view class="h-[150rpx]"></view>

    <!-- 保存按钮 -->
    <view class="fixed bottom-0 left-0 right-0 bg-white shadow-lg p-[24rpx] max-w-[750rpx] mx-auto">
      <nut-button 
        type="primary" 
        block 
        class="h-[88rpx] text-[32rpx] font-bold rounded-[24rpx] bg-[#165DFF]"
        @click="saveProfile"
        :loading="saving"
      >
        {{ saving ? '保存中...' : '保存个人资料' }}
      </nut-button>
    </view>
  </Page>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import Taro from '@tarojs/taro'
import { showToast } from '@tarojs/taro'
import { IconFont } from '@nutui/icons-vue-taro'
import PageHeader from '@/components/PageHeader.vue'
import {post} from "@/utils/request";

/**
 * 个人信息编辑页面
 * @description 头像上传、基本信息编辑、技能标签管理、服务范围选择，严格按设计稿和Cursor规则实现。
 * @performance 表单数据响应式，图片压缩上传，防重复提交。
 */

interface FormData {
  avatarUrl: string
  name: string
  briefIntroduction: string
  skills: string[]
  serviceScopeIds: string[]
}
//服务范围选项参数
interface ServiceOption {
  id: number
  name: string
  checked: boolean
}
//获取到的服务范围选项包含的参数
interface  serviceColumn{
  industry_id:string
  update_time: string
  create_time: string
  name: string
  id: number
  pic: string
}
//获取到的数据的格式
interface serviceItem {
  columns: serviceColumn;
  columnNames: string[];
  columnValues: (null | number | string)[];
}

//获取服务范围列表
post("/dictionary/serviceScope").then(res=>{
  serviceOptions.value = res.data.map((item: serviceItem)=>({
    id: item.columns.id,
    name: item.columns.name,
    checked: false
  }))
  console.log("接收的服务选项",serviceOptions.value)
})

const formData = reactive<FormData>({
  avatarUrl: '',
  name: '张三',
  briefIntroduction: '前端开发工程师，5年开发经验，擅长Vue和React',
  skills: ['HTML5', 'CSS3', 'JavaScript'],
  serviceScopeIds: []
})

const newSkill = ref('')
const saving = ref(false)

const serviceOptions = ref<ServiceOption[]>([
  { id: 1, name: '前端开发', checked: true },
  { id: 2, name: '网站建设', checked: true },
  { id: 3, name: '技术咨询', checked: false },
  { id: 4, name: 'UI设计', checked: false },
  { id: 5, name: '后端开发', checked: false },
  { id: 6, name: '移动端开发', checked: false }
])


async function chooseAvatar() {
  try {
    const res = await Taro.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera']
    })
    
    if (res.tempFilePaths && res.tempFilePaths.length > 0) {
      // 上传头像
      await uploadAvatar(res.tempFilePaths[0])

    }
  } catch (error) {
    console.error('选择头像失败:', error)
  }
}

async function uploadAvatar(filePath: string) {
  try {
    showToast({ title: '上传中...', icon: 'loading' })
    
    const token = Taro.getStorageSync('token')
    const uploadRes = await Taro.uploadFile({
      url: '/file/upload',
      filePath,
      name: 'file',
      header: {
        token: token
      }
    })
    formData.avatarUrl = filePath
    const result = JSON.parse(uploadRes.data)
    console.log("result", result)
    // if (result.code === 200) {
    //   formData.avatar = result.data.url
    //   showToast({ title: '头像上传成功', icon: 'success' })
    // } else {
    //   showToast({ title: '上传失败', icon: 'error' })
    // }
  } catch (error) {
    console.error('上传头像失败:', error)
    showToast({ title: '上传失败', icon: 'error' })
  }
}

function addSkill() {
  const skill = newSkill.value.trim()
  if (skill && !formData.skills.includes(skill)) {
    formData.skills.push(skill)
    newSkill.value = ''
  }
}

function removeSkill(index: number) {
  formData.skills.splice(index, 1)
}

function onSkillKeyPress(e: any) {
  if (e.key === 'Enter') {
    addSkill()
  }
}

async function saveProfile() {
  if (saving.value) return
  
  saving.value = true
  
  try {
    // 收集服务选项
    const selectedServices = serviceOptions.value
      .filter(service => service.checked)
      .map(service => service.id)
    
    const profileData = {
      ...formData,
      services: selectedServices
    }
    
    // 这里可以调用API保存数据
    //console.log('接收的服务选项:', serviceOptions.value)
    //console.log('服务选项:', selectedServices)
    console.log('保存个人资料:', profileData)
    
    // 模拟API调用
    //await new Promise(resolve => setTimeout(resolve, 1000))
    //API调用
     post('/my/updateUser',profileData).then(res=>{
      if(res.code === 0){
        showToast({ title: '保存成功', icon: 'success' })
      }
    })

    //showToast({ title: '保存成功', icon: 'success' })
    
    // 返回上一页
    /*setTimeout(() => {
      Taro.navigateBack()
    }, 1500)*/
    
  } catch (error) {
    console.error('保存失败:', error)
    showToast({ title: '保存失败', icon: 'error' })
  } finally {
    saving.value = false
  }
}
</script> 